<?php





namespace app\crm\model;



use app\mini\model\AdminUser;
use think\facade\Db;

use app\admin\model\Common;
use app\admin\model\ShopModel;

class ReturnVist extends Common

{



    /**

     * 为了数据库的整洁，同时又不影响Model和Controller的名称

     * 我们约定每个模块的数据表都加上相同的前缀，比如CRM模块用crm作为数据表前缀

     */

    protected $name = 'return_vist';



    /**
     * 列表
     * @param  array $request 请求参数
     * @return array
     */

    public function getDataList(array $request): array
    {
        try {
            // 1. 分页参数处理
            $page = max(1, intval($request['page'] ?? 1));
            $limit = max(1, intval($request['limit'] ?? 15));
            $offset = ($page - 1) * $limit;

            // 2. 初始化查询条件
            $where = [];
            $customerIds = [];

            // 3. 客户ID条件
            if (!empty($request['customer_id'])) {
                $where[] = ['a.customer_id', '=', intval($request['customer_id'])];
            }

            // 4. 制作人/店铺ID条件
            $userIds = [];
            if (!empty($request['make_id'])) {
                $shopIds = Db::name('shop')->where('make_id', intval($request['make_id']))->column('shop_id');
                $userIds = Db::name('customer')->where('shop_id', 'in', $shopIds)->column('id');
            }

            if (!empty($request['shop_id'])) {
                $shopIds = Db::name('shop')->where('shop_id', intval($request['shop_id']))->column('shop_id');
                $shopUserIds = Db::name('customer')->where('shop_id', 'in', $shopIds)->column('id');
                $userIds = array_merge($userIds, $shopUserIds);
            }

            if (!empty($userIds)) {
                $where[] = ['a.customer_id', 'in', array_unique($userIds)];
            }

            // 5. 导出条件
            if (!empty($request['export']) && $request['export'] == 1 && !empty($request['id'])) {
                $where[] = ['a.id', 'in', array_map('intval', (array)$request['id'])];
            }

            // 6. 客户名称/电话搜索
            if (!empty($request['customer_name_or_phone'])) {
                $searchTerm = trim($request['customer_name_or_phone']);
                $customerIds = Db::name('customer')
                    ->whereOr([
                        ['customer_name', 'like', "%{$searchTerm}%"],
                        ['telephone', 'like', "%{$searchTerm}%"]
                    ])
                    ->column('id');

                if (!empty($customerIds)) {
                    $where[] = ['a.customer_id', 'in', $customerIds];
                } else {
                    // 没有匹配结果时返回空数据
                    return ['list' => [], 'dataCount' => 0];
                }
            }

            // 7. 回访时间条件
            if(!empty($request['start_time']) || !empty($request['end_time']))
            {

                if(!empty($request['start_time']))
                {
                    $start = strtotime($request['start_time'].'00:00:00');

                }else
                {
                    $start = strtotime(time().'00:00:00');
                }
                if(!empty($request['end_time']))
                {
                    $over = strtotime($request['end_time'].'23:59:59');
                }else
                {
                    $over = strtotime(time().'23:59:59');
                }
                $where[] = ['a.return_visit_time','between',[$start, $over]];
            }


            // 8. 店铺ID条件
            if (!empty($request['shopIds'])) {
                $where[] = ['b.shop_id', 'in', array_map('intval', (array)$request['shopIds'])];
            }

            if(!empty($request['work_name'])){
                $adminuser_ids = AdminUser::where('realname','like','%'.$request['work_name'].'%')->column('id');
                $where[] = ['a.return_visitor','in',$adminuser_ids];
            }




            // 9. 数据查询
            $query = Db::name('return_vist')
                ->alias('a')
                ->leftJoin('customer b', 'b.id = a.customer_id');

            // 10. 获取总数
            $dataCount = $query->where($where)->count();

            // 11. 获取数据列表
            $list = [];
            if ($dataCount > 0) {
                $field = [
                    'a.id', 'a.customer_id', 'a.create_time', 'a.return_visitor', 'a.type',
                    'a.return_visit_time', 'a.return_visit_content', 'a.next_call_back','a.next_status',
                    'b.customer_name', 'b.telephone', 'b.shop_id' // 直接获取客户信息
                ];

                $list = $query
                    ->field($field)
                    ->order('a.id', 'DESC')
                    ->limit($offset, $limit)
                    ->select()
                    ->toArray();

                // 12. 准备批量查询的数据
                $userIdArr = array_unique(array_column($list, 'return_visitor'));
                $shopIdArr = array_unique(array_column($list, 'shop_id'));

                // 13. 批量获取用户和店铺信息
                $userList = $userIdArr ? Db::name('admin_user')
                    ->where('id', 'in', $userIdArr)
                    ->column('realname', 'id') : [];

                $shopList = $shopIdArr ? Db::name('shop')
                    ->where('shop_id', 'in', $shopIdArr)
                    ->column('shop_name', 'shop_id') : [];

                // 14. 处理列表数据
                foreach ($list as &$item)
                {
                    $item['return_visitor_name'] = $userList[$item['return_visitor']] ?? '';
                    $item['shop_name'] = $shopList[$item['shop_id']] ?? '';
                    $item['return_visit_time'] = $item['return_visit_time'] > 0
                        ? date('Y-m-d H:i:s', $item['return_visit_time'])
                        : '';
                    $item['next_call_back'] = $item['next_call_back'] > 0
                        ? date('Y-m-d H:i:s', $item['next_call_back'])
                        : '';

                    // 类型转换 - 新增部分
                    $typeMapping = [
                        1 => '邀约回访',
                        2 => '术后回访',
                        3 => '激活回访'
                    ];
                    $item['type_text'] = $typeMapping[$item['type']] ?? '未知类型';
                }
            }

            return [
                'list' => $list,
                'dataCount' => $dataCount
            ];

        } catch (\Exception $e) {
            // 记录错误日志
            $this->error = '获取数据失败，请稍后重试';
            return ['list' => [], 'dataCount' => 0];
        }
    }


    /**
     * 添加
     * @param  array $request 请求参数
     * @return array
     */
    public function addData(array $request): array
    {
        // 前置校验
        if (empty($request['return_visit_content']))
        {
            $this->error = '请录入回访的内容';
            return [];
        }

        $customerId = $request['customer_id'] ?? 0;
        if (empty($customerId))
        {
            $this->error = '请选择回访的客户';
            return [];
        }

        Db::startTrans();
        try
        {
            $vistId = $request['vistId'] ?? null;
            $userId = $request['user_id'] ?? 0;
            $nextTime = $request['next_time'] ? strtotime($request['next_time']) : 0;

            // 构建回访数据（包含下次预约时间）
            $visitData = [
                'return_visit_time'    => time(),
                'return_visit_content' => $request['return_visit_content'],
                'return_visitor'       => $userId,
                'next_call_back'       => $nextTime,
                'next_status'           => $nextTime > 0 ? 1 : 0 // 新字段：0=无需回访，1=待回访
            ];

            // 新增回访需补充数据
            if (!$vistId)
            {
                $visitData['customer_id'] = $customerId;
                $visitData['type'] = $request['type'] ?? 1;
                $visitData['create_time'] = time();
            }

            // 获取员工信息并构建客户更新数据
            $staffInfo = Db::name('admin_user')->where('id', $userId)->find();
            $customerUpdate = ['last_kftime' => time()];

            // 根据员工类型设置不同的下次回访时间字段
            if (!empty($staffInfo['shop_person_id']))
            {
                $customerUpdate['shop_next_time'] = $nextTime;
            } else {
                $customerUpdate['kf_next_time'] = $nextTime;
            }

            // 更新客户信息
            Db::name('customer')->where('id', $customerId)->update($customerUpdate);

            // 保存/更新回访记录
            if ($vistId)
            {
                $this->where('id', $vistId)->update($visitData);
                $recordId = $vistId;
            }else
            {
                $recordId = $this->insertGetId($visitData);
            }
            // +++ 新增：检查并更新今天待回访的记录 +++
            if ($nextTime > 0)
            {
                // 获取今天的时间范围
                $todayStart = strtotime(date('Y-m-d 00:00:00'));
                $todayEnd = strtotime(date('Y-m-d 23:59:59'));
                $currentTime = time();
                
                // 检查条件：今天待回访 + 已过预约时间 + 未回访状态
                $updateCondition = [
                    ['customer_id', '=', $customerId],
                    ['next_call_back', 'between', [$todayStart, $todayEnd]],
                    ['next_status', '=', 1], // 待回访状态
                    ['id', '<>', $recordId] // 排除刚添加的记录
                ];
                
                // 查找今天待回访的记录
                $pendingRecords = $this->where($updateCondition)->select();
                
                if(!empty($pendingRecords))
                {
                    foreach ($pendingRecords as $record)
                    {
                        // 如果当前时间已超过预约时间
                        if ($currentTime > $record['next_call_back'])
                        {
                            // 更新为已回访状态
                            Db::name('return_vist')
                                ->where('id', $record['id'])
                                ->update(['next_status' => 2]); // 2=已回访
                        }
                    }
                }
            }
            // --- 结束新增部分 ---
            Db::commit();
            return ['id' => $recordId];

        } catch (\Exception $e) {
            Db::rollback();
            $this->error = '操作失败: ' . $e->getMessage();
            return [];
        }
    }



    ///// 定时回访记录 /////

    public function getList(array $request): array

    {

        // echo "<pre>";
        // print_r($request);
        // exit;

        $is_vist = $request['is_vist'] ?? '1';

        $request['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;

        $request['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 10;

        $stime = strtotime('-1 days');

        // $etime = strtotime('+7 days');

        $startTime = $request['yjreturn_visit_time'] ?? '';

        $endTime = $request['yjreturn_visit_time2'] ?? '';

        // echo "时间：".$startTime.'-'.$endTime;

        $start_time = strtotime($startTime.'00:00:00');


        $end_time = $endTime>0 ? strtotime($endTime.'23:59:59') : '';





        $userInfo = $request['userInfo']??[];

        if ($userInfo == []){

            $data              = [];

            $data['list']      = $list ?? [];

            $data['dataCount'] = $dataCount ?? 0;

            return $data;

        }

        $where = [];

        if($is_vist == '1'){
            array_push($where,['r.return_visit_time','=','0']);
        }else{
            array_push($where,['r.return_visit_time','>','0']);
        }

        if($request['shopIds']){
            array_push($where,['c.shop_id','in',$request['shopIds']]);
        }

        $shop_person_id = $userInfo['shop_person_id'] ?? '';
        $groupId = $userInfo['group_id'] ?? '';



        if(empty($shop_person_id)){
            if($start_time){
                array_push($where,['c.kf_next_time','>',"$start_time"]);
            }

            if($end_time){
                array_push($where,['c.kf_next_time','<',"$end_time"]);
            }

            if($groupId == 50){
                array_push($where,['c.operator','=',$userInfo['id']]);
                // echo "客服";
            }else{
                // echo "非客服";
            }

        }else{

            if($start_time){
                array_push($where,['c.shop_next_time','>',"$start_time"]);
            }

            if($end_time){
                array_push($where,['c.shop_next_time','<',"$end_time"]);
            }
            // echo "门店员工";

        }



        $dataCounts = Db::name('return_vist')->alias('r')
            ->join('customer c','c.id = r.customer_id','LEFT')
            ->where($where)->count();
            // echo "<pre>";
            // print_r($dataCounts);
            // echo "</pre>";exit;
        if($dataCounts){
            $filed = ['c.id', 'c.customer_name', 'c.sex','c.telephone', 'c.birthday', 'c.effective_entry', 'c.shop_id','c.source_id','c.effective_entry','c.status','c.create_time','c.first_time','c.second_time','c.member_classification','c.turn_status','c.age','c.membership_leve','c.nurse_id','c.repair_progress','c.consumption','c.new_join_shop_time','c.final_consumption','c.final_service','c.be_overdue_time','c.cj_time','c.cj_money','c.operator','c.last_kftime','c.difficulty_level','c.kf_next_time','c.shop_next_time'];
            $list = Db::name('return_vist')->alias('r')
                            ->join('customer c','c.id = r.customer_id','LEFT')
                            ->where($where)
                            ->field($filed)
                            ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])
                            ->select()->toArray();

            // echo "<pre>";
            // print_r($list);

            $shopIds        = array_values(array_unique(array_column($list, 'shop_id')));
            $nurseIds       = array_values(array_unique(array_column($list, 'nurse_id')));
            $operatorIds    = array_values(array_unique(array_column($list, 'operator')));

            //获取店铺数据
            $shopList       = Db::name('shop')->where('shop_id', 'in', $shopIds)->column('shop_name,market_name', 'shop_id');
            //获取员工数据
            $personList     = Db::name('shop_person')->where('id', 'in', $nurseIds)->column('name', 'id');
            //获取会员等级
            $gradeList      = Db::name('customer_grade')->column('name', 'id');
            $adminList      = Db::name('admin_user')->where('id', 'in', $operatorIds)->column('realname', 'id');
            //基础配置
            $settingList    = Db::name('setting')->column('name', 'id');
            $sexArr         = ['0' => '未知', '1' => '男', '2' => '女'];
            $EntryArr       = ['1' => '是', '2' => '否'];

            foreach($list as $key => $val){
                if ($val['birthday']) {
                    $setData            = array();
                    $setData['age']     = bcsub(date('Y'),date('Y',$val['birthday']),0);
                    $setData['id']      = $val['id'];
                    $saveAll[]          = $setData;
                    $list[$key]['age']  = $setData['age'];
                }
            }

            foreach ($list as $key => $val) {
                $list[$key]['sex']             = $sexArr[$val['sex']] ?? '未知';
                $list[$key]['effective_entry'] = $EntryArr[$val['effective_entry']] ?? '否';
                $list[$key]['shop_name']       = $shopList[$val['shop_id']]['shop_name'] ?? '';
                // $list[$key]['market_name']       = $shopList[$val['shop_id']]['market_name'] ?? '';
                // $list[$key]['birthday']        = $val['birthday'] ? date('Y-m-d', $val['birthday']) : '';
                $list[$key]['source_name']     = $settingList[$val['source_id']] ?? '';

                // 负责人名称
                $list[$key]['nurse_name']      = $personList[$val['nurse_id']] ?? '';

                // 客服名称
                $list[$key]['operator']      = $adminList[$val['operator']] ?? '';

                if(empty($shop_person_id)){
                    $list[$key]['next_visit_time'] = $val['kf_next_time'] > 0 ? date('Y-m-d',$val['kf_next_time']) : '';
                }else{
                    $list[$key]['next_visit_time'] = $val['shop_next_time'] > 0 ? date('Y-m-d',$val['kf_next_time']) : '';
                }

                // 客户的名称
                $list[$key]['customer_service_name'] = $adminList[$val['operator']] ?? '';
                $list[$key]['customer_name_phone'] = $val['customer_name'].'/'.$val['telephone'];
            }
        }

        // echo "<pre>";
        // print_r($list);

        $data              = [];

        $data['list']      = $list ?? [];

        $data['dataCount'] = $dataCounts ?? 0;

        return $data;


    }



    public function addDs(array $request): array
    {
        Db::startTrans();
        try {
            // 1. 基础数据验证
            $requiredFields = [
                'return_visit_content' => '请录入回访的内容',
                'user_id' => '请提供操作人ID'
            ];

            foreach ($requiredFields as $field => $errorMsg) {
                if (empty($request[$field])) {
                    $this->error = $errorMsg;
                    return [];
                }
            }

            $customerId = $request['customer_id'] ?? 0;
            $vistId = $request['vistId'] ?? 0;
            $isUpdate = !empty($vistId);

            // 2. 新增操作需要验证客户ID
            if (!$isUpdate && empty($customerId)) {
                $this->error = '请选择回访的客户';
                return [];
            }

            // 3. 准备回访数据
            $currentTime = time();
            $visitData = [
                'return_visit_content' => $request['return_visit_content'],
                'return_visit_time'    => $currentTime,
                'return_visitor'       => $request['user_id'],
                'type'                 => $request['type'] ?? 1
            ];

            // 4. 处理客户信息更新
            $nextTime = !empty($request['next_time']) ? strtotime($request['next_time']) : 0;
            $staffInfo = Db::name('admin_user')->where('id', $request['user_id'])->find();
            $isShopStaff = !empty($staffInfo['shop_person_id']);

            $customerUpdate = [
                'last_kftime' => $currentTime,
                $isShopStaff ? 'shop_next_time' : 'kf_next_time' => $nextTime
            ];

            // 5. 更新客户表
            Db::name('customer')->where('id', $customerId)->update($customerUpdate);

            // 6. 保存回访记录
            if ($isUpdate) {
                $this->where('id', $vistId)->update($visitData);
                $visitId = $vistId;
            } else {
                $visitData['customer_id'] = $customerId;
                $visitData['create_time'] = $currentTime;
                $visitId = $this->insertGetId($visitData);
            }

            // 7. 处理下次回访记录
            if ($nextTime > 0)
            {
                $nextVisitData = [
                    'customer_id'   => $customerId,
                    'next_call_back' => $nextTime,
                    'create_time'   => $currentTime,
                    'next_type'      => $isShopStaff ? 'shop' : 'kf'
                ];
                Db::name('return_vist')->insert($nextVisitData);
            }

            Db::commit();
            return ['id' => $visitId];

        } catch (\Exception $e) {
            Db::rollback();
            $this->error = '操作失败: ' . $e->getMessage();
            return [];
        }
    }




     public function addDsXh(array $request): array
    {



        try {

            $id      = $request['id'] ?? 0;

            $user_id = $request['user_id'] ?? 0;

            $saveData['return_visit_time']    = time();

            $saveData['return_visit_content'] = $request['return_visit_content'] ?? '';



            $find = Db::name('return_vist_ds')->where('id','=',$id)->find();

            if(!$find){

                $this->error = '预约回访记录不存在';

                return [];

            }

            if ($find['return_visit_time'] > 0) {

                $this->error = '预约回访已被处理';

                return [];

            }

            if(empty($saveData['return_visit_content'])){

                $this->error = '预约回访记录不能为空';

                return [];

            }

            if ($find['user_id'] != $user_id) {

                $this->error = '请处理属于自己的预约回访';

                return [];

            }

            Db::name('return_vist_ds')->where('id','=',$id)->update($saveData);

            $this->error = '预约回访处理成功';

            return ['id'=>$id??0];

        } catch (\Exception $e) {

            $this->error = '预约回访处理失败';

            return [];

        }

    }


    /**

     * 修复方案列表

     * @param  array $request 请求参数

     * @return array

     */

    public function getRepairPlanList(array $request): array

    {
        $request['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;

        $request['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;

        $customer_id = $request['customer_id'];

        $where = [];

        array_push($where,['customer_id','=',$customer_id]);

        $field = ['id','customer_id', 'create_time', 'repair_visitor', 'repair_plan_time', 'repair_plan_content'];

        $list  = Db::name('repair_plan')->where($where)->field($field)->order('id DESC')->limit(($request['page'] - 1) * $request['limit'], $request['limit'])->select()->toArray();

        $userIdArr = array_unique(array_column($list, 'repair_visitor'));

        $userList  = Db::name('admin_user')->where('id', 'in', $userIdArr)->column(['realname'], 'id');

        $customerIdArr = array_unique(array_column($list, 'customer_id'));

        $customerList  = Db::name('customer')->where('id', 'in', $customerIdArr)->column(['customer_name,telephone','shop_id'], 'id');

        $shopIdArr = array_unique(array_column($customerList, 'shop_id'));

        $shopList  = Db::name('shop')->where('shop_id', 'in', $shopIdArr)->column(['shop_name'], 'shop_id');

        foreach ($list as $key => $val) {

            $list[$key]['repair_visitor_name'] = $userList[$val['repair_visitor']] ?? '';

            $list[$key]['customer_name']       = $customerList[$val['customer_id']]['customer_name'] ?? '';

            $list[$key]['telephone']       = $customerList[$val['customer_id']]['telephone'] ?? '';

            $list[$key]['shop_name']       = $shopList[$customerList[$val['customer_id']]['shop_id']] ?? '';

            $list[$key]['repair_plan_time']   = date('Y-m-d H:i:s',$val['repair_plan_time']);

        }


        $data              = [];

        $data['list']      = $list ?? [];

        $data['dataCount'] = count($list) ?? 0;

        return $data;


    }


    /**

     * 添加修护方案

     * @param  array $request 请求参数

     * @return array

     */

    public function addRepairData(array $request): array

    {

        try {

            $addData['customer_id']         = $request['customer_id'] ?? 0;

            $addData['repair_plan_time']   = time();

            $addData['repair_plan_content']= $request['repair_plan_content'] ?? '';

            $addData['repair_visitor']      = $request['user_id'] ?? 0;

            $addData['create_time']         = time();

            if ($addData['customer_id'] == 0) {

                // code...

                $this->error = '请选择添加方案的客户';

                return [];

            }

            // if (empty($addData['return_visit_time'])) {

            //     // code...

            //     $this->error = '请选择回访的时间';

            //     return [];

            // }

            if (empty($addData['repair_plan_content'])) {

                // code...

                $this->error = '请录入修复方案的内容';

                return [];

            }


            $save = [

                    'last_kftime' => time()

                ];

            Db::name('customer') -> where('id','=',$addData['customer_id'])->save($save);

            // $id = $this->insertGetId($addData);

            $id = Db::name('repair_plan')->insertGetId($addData);

            return ['id'=>$id];

        } catch (\Exception $e) {

            $this->error = '添加失败';

            return [];

        }

    }
    /*模型关联 shop表 */
    public function shop(){

        return $this->hasOne(ShopModel::class);

    }

}

